const pageHelper = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('project_helpers_config.js').(_, __, helper) => helper.replace('.js', '');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { resourcesStore } = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/project/resourcesStore');
const dayjs = require('dayjs');
const wxCharts = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getNpmPath('libs_migration(_, __, pkg, file) => file ? '/' + file : ''');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    projectId: '',
    projectName: '',
    
    // 周期选择
    periodOptions: [
      { text: '本周', value: 'week' },
      { text: '本月', value: 'month' },
      { text: '本季度', value: 'quarter' },
      { text: '本年', value: 'year' },
      { text: '全部', value: 'all' }
    ],
    selectedPeriod: 'month',
    
    // 图表数据
    workloadChartData: {},
    costChartData: {},
    teamDistributionData: {},
    departmentDistributionData: {},
    
    // 折叠面板
    activeCollapse: ['1', '2', '3', '4'],
    
    // 展示模式
    viewMode: 'chart', // chart, table
    
    // 是否显示导出按钮
    canExport: false,
    
    // UI状态
    isLoading: true,
    hasError: false,
    errorMsg: '',
    
    // 图表实例
    workloadChart: null,
    costChart: null,
    roleChart: null,
    departmentChart: null,
    
    // 折叠面板状态
    expandedPanels: {
      workload: true,
      cost: false,
      role: false,
      department: false
    }
  },
  
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_statistics_resources' });
    
    // 创建MobX绑定
    this.storeBindings = createStoreBindings(this, {
      store: resourcesStore,
      fields: [
        'teamSize', 
        'plannedWorkload', 
        'actualWorkload',
        'usageRate',
        'workloadData',
        'costData',
        'roleData',
        'departmentData',
        'workloadTableData',
        'costTableData',
        'roleTableData',
        'departmentTableData',
        'isDataLoaded'
      ],
      actions: ['fetchResourcesData', 'changePeriod', 'resetStore']
    });
    
    if (options.id) {
      // 设置项目ID
      this.setData({ 
        projectId: options.id,
        projectName: options.name || '项目资源统计'
      });
      
      // 初始加载数据
      this.loadData();
    } else {
      // 尝试从上下文获取当前项目
      const currentProject = projectContext.getCurrentProjectInfo();
      if (currentProject) {
        this.setData({
          projectId: currentProject.id,
          projectName: currentProject.projectType || '项目资源统计'
        });
        
        // 初始加载数据
        this.loadData();
      } else {
        pageHelper.showErrorToast('未找到项目信息');
        setTimeout(() => wx.navigateBack(), 1500);
      }
    }
    
    // 检查用户权限
    this._checkUserPermission();
  },
  
  // 加载数据
  async loadData() {
    try {
      this.setData({ isLoading: true, hasError: false });
      await this.fetchResourcesData({
        projectId: this.data.projectId,
        period: this.data.selectedPeriod
      });
      this.setData({ isLoading: false });
      
      // 初始化图表（仅在首次加载或切换视图模式后）
      if (this.data.viewMode === 'chart') {
        this.initCharts();
      }
    } catch (error) {
      console.error('加载资源数据失败:', error);
      this.setData({
        isLoading: false,
        hasError: true,
        errorMsg: error.message || '加载数据失败，请重试'
      });
    }
  },
  
  // 准备图表数据
  _prepareChartData: function() {
    if (!this.data.resourcesStatistics) return;
    
    const statistics = this.data.resourcesStatistics;
    const resources = statistics.resources;
    
    // 工作量图表数据
    this.setData({
      workloadChartData: {
        series: [
          { name: '计划工作量', value: resources.workload.planned },
          { name: '实际工作量', value: resources.workload.actual },
          { name: '剩余工作量', value: resources.workload.remaining }
        ]
      }
    });
    
    // 成本图表数据
    this.setData({
      costChartData: {
        series: [
          { name: '计划成本', value: resources.costUsage.planned },
          { name: '实际成本', value: resources.costUsage.actual },
          { name: '剩余成本', value: resources.costUsage.remaining }
        ]
      }
    });
    
    // 团队角色分布
    if (resources.teamDistribution && resources.teamDistribution.length > 0) {
      this.setData({
        teamDistributionData: {
          series: resources.teamDistribution.map(item => ({
            name: item.role,
            value: item.count
          }))
        }
      });
    }
    
    // 部门分布
    if (resources.departmentDistribution && resources.departmentDistribution.length > 0) {
      this.setData({
        departmentDistributionData: {
          series: resources.departmentDistribution.map(item => ({
            name: item.department,
            value: item.count
          }))
        }
      });
    }
  },
  
  // 切换周期
  onPeriodChange: function(e) {
    const period = e.currentTarget.dataset.value;
    this.setData({ selectedPeriod: period });
    
    // 设置周期并刷新数据
    this.changePeriod(period);
    this.loadData();
  },
  
  // 切换展示模式
  onViewModeChange: function(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({ viewMode: mode });
    
    // 如果切换到图表视图，需要初始化图表
    if (mode === 'chart') {
      // 延迟初始化，确保DOM已渲染
      setTimeout(() => {
        this.initCharts();
      }, 300);
    }
  },
  
  // 初始化所有图表
  initCharts() {
    if (this.data.workloadData && this.data.workloadData.length > 0) {
      this.initWorkloadChart();
    }
    
    if (this.data.costData && this.data.costData.length > 0) {
      this.initCostChart();
    }
    
    if (this.data.roleData && this.data.roleData.length > 0) {
      this.initRoleChart();
    }
    
    if (this.data.departmentData && this.data.departmentData.length > 0) {
      this.initDepartmentChart();
    }
  },
  
  // 初始化工时图表
  initWorkloadChart() {
    const query = wx.createSelectorQuery();
    query.select('#workloadChart').boundingClientRect().exec((res) => {
      if (!res || !res[0]) return;
      
      const canvasId = 'workloadCanvas';
      const ctx = wx.createCanvasContext(canvasId);
      const chart = new wxCharts({
        canvasId: canvasId,
        type: 'column',
        categories: this.data.workloadData.map(item => item.name),
        series: [{
          name: '计划工时',
          data: this.data.workloadData.map(item => item.planned),
          format: (val) => val + 'h'
        }, {
          name: '实际工时',
          data: this.data.workloadData.map(item => item.actual),
          format: (val) => val + 'h'
        }],
        yAxis: {
          title: '工时(h)',
          min: 0
        },
        width: res[0].width,
        height: 300,
        legend: true,
        dataLabel: true,
        extra: {
          column: {
            width: 20
          }
        }
      });
      
      this.setData({
        workloadChart: chart
      });
    });
  },
  
  // 初始化成本图表
  initCostChart() {
    const query = wx.createSelectorQuery();
    query.select('#costChart').boundingClientRect().exec((res) => {
      if (!res || !res[0]) return;
      
      const canvasId = 'costCanvas';
      const ctx = wx.createCanvasContext(canvasId);
      const chart = new wxCharts({
        canvasId: canvasId,
        type: 'line',
        categories: this.data.costData.map(item => item.date),
        series: [{
          name: '计划成本',
          data: this.data.costData.map(item => item.planned),
          format: (val) => val + '元'
        }, {
          name: '实际成本',
          data: this.data.costData.map(item => item.actual),
          format: (val) => val + '元'
        }],
        yAxis: {
          title: '成本(元)',
          min: 0
        },
        width: res[0].width,
        height: 300,
        legend: true,
        dataLabel: false,
        extra: {
          lineStyle: 'curve'
        }
      });
      
      this.setData({
        costChart: chart
      });
    });
  },
  
  // 初始化角色分布图表
  initRoleChart() {
    const query = wx.createSelectorQuery();
    query.select('#roleChart').boundingClientRect().exec((res) => {
      if (!res || !res[0]) return;
      
      const canvasId = 'roleCanvas';
      const ctx = wx.createCanvasContext(canvasId);
      const chart = new wxCharts({
        canvasId: canvasId,
        type: 'pie',
        series: this.data.roleData.map(item => ({
          name: item.name,
          data: item.count
        })),
        width: res[0].width,
        height: 300,
        dataLabel: true
      });
      
      this.setData({
        roleChart: chart
      });
    });
  },
  
  // 初始化部门分布图表
  initDepartmentChart() {
    const query = wx.createSelectorQuery();
    query.select('#departmentChart').boundingClientRect().exec((res) => {
      if (!res || !res[0]) return;
      
      const canvasId = 'departmentCanvas';
      const ctx = wx.createCanvasContext(canvasId);
      const chart = new wxCharts({
        canvasId: canvasId,
        type: 'pie',
        series: this.data.departmentData.map(item => ({
          name: item.name,
          data: item.count
        })),
        width: res[0].width,
        height: 300,
        dataLabel: true
      });
      
      this.setData({
        departmentChart: chart
      });
    });
  },
  
  // 切换折叠面板
  togglePanel(e) {
    const panelName = e.currentTarget.dataset.panel;
    const expandedPanels = { ...this.data.expandedPanels };
    expandedPanels[panelName] = !expandedPanels[panelName];
    
    this.setData({ expandedPanels });
    
    // 如果展开了面板且是图表模式，初始化相应的图表
    if (expandedPanels[panelName] && this.data.viewMode === 'chart') {
      switch (panelName) {
        case 'workload':
          this.initWorkloadChart();
          break;
        case 'cost':
          this.initCostChart();
          break;
        case 'role':
          this.initRoleChart();
          break;
        case 'department':
          this.initDepartmentChart();
          break;
      }
    }
  },
  
  // 导出报告
  exportReport: function() {
    // 显示导出选项
    wx.showActionSheet({
      itemList: ['导出为Excel', '导出为PDF'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 导出Excel
          this._exportExcel();
        } else if (res.tapIndex === 1) {
          // 导出PDF
          this._exportPDF();
        }
      }
    });
  },
  
  // 导出Excel
  _exportExcel: function() {
    wx.showLoading({ title: '正在导出...' });
    
    // 调用云函数导出Excel
    wx.cloud.callFunction({
      name: 'exportStatistics',
      data: {
        type: 'excel',
        projectId: this.data.projectId,
        module: 'resources',
        period: this.data.selectedPeriod
      }
    }).then(res => {
      wx.hideLoading();
      
      if (res.result && res.result.fileID) {
        // 下载文件
        wx.cloud.downloadFile({
          fileID: res.result.fileID,
          success: result => {
            // 保存文件到本地
            wx.saveFile({
              tempFilePath: result.tempFilePath,
              success: saveRes => {
                wx.openDocument({
                  filePath: saveRes.savedFilePath,
                  showMenu: true
                });
              },
              fail: err => {
                pageHelper.showErrorToast('保存文件失败');
              }
            });
          },
          fail: err => {
            pageHelper.showErrorToast('下载文件失败');
          }
        });
      } else {
        pageHelper.showErrorToast('导出失败');
      }
    }).catch(err => {
      wx.hideLoading();
      pageHelper.showErrorToast('导出失败：' + err.message);
    });
  },
  
  // 导出PDF
  _exportPDF: function() {
    pageHelper.showSuccessToast('PDF导出功能开发中');
  },
  
  // 检查用户权限
  _checkUserPermission: function() {
    // 从全局用户权限检查（实际实现可能不同）
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    const userPermissions = userInfo.permissions || {};
    
    // 检查是否有导出权限
    const canExport = userPermissions.project?.admin === true || 
                      userPermissions.statistics?.export === true;
    
    this.setData({ canExport });
  },
  
  onPullDownRefresh: function() {
    // 下拉刷新
    this.loadData().then(() => {
      wx.stopPullDownRefresh();
    }).catch(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  onShareAppMessage: function() {
    return {
      title: `${this.data.projectName}资源使用统计`,
      path: `/projects/plm/pages/project/statistics/resources/resources?id=${this.data.projectId}&name=${this.data.projectName}`
    };
  },
  
  onUnload: function() {
    // 销毁MobX绑定
    this.storeBindings.destroyStoreBindings();
    // 重置Store
    this.resetStore();
  }
}); 